<template>
  <div>
    <el-row class="row-actions">
      <el-col :span="4">
        <el-button
          size="mini"
          type="danger"
          @click="$router.push({ path: '/screen/index' })"
          >关闭</el-button
        >
        <el-button size="mini" type="primary" @click="commit">保存</el-button>
        <el-button size="mini" @click="getScreenPreviewUrl($route.query.id)">
          预览
        </el-button>
      </el-col>

      <el-col :span="2">
        <el-input
          size="mini"
          type="number"
          v-model="form.width"
          placeholder="width"
        ></el-input>
      </el-col>
      <el-col :span="2">
        <el-input
          size="mini"
          type="number"
          v-model="form.height"
          placeholder="height"
        ></el-input>
      </el-col>
      <el-col :span="2">
        <el-select v-model="form.scale" placeholder="缩放" size="mini">
          <el-option :label="i" :value="i" v-for="i in [1.5,1.2,1,0.9,0.8,0.7,0.5]" :key="i"> </el-option>
        </el-select>
      </el-col>
      <el-col :span="2">
        <el-button type="primary" size="mini" @click="reloadPanel"
          >刷新面板</el-button
        >
      </el-col>
      <el-col :span="10">
        <el-button
          size="mini"
          :type="layervisible ? 'primary' : ''"
          @click="layervisible = !layervisible"
          >图层</el-button
        >
        <el-button size="mini" @click="$refs.layerTemplatesForm.show({})"
          >导入图层模板</el-button
        >
        &nbsp; &nbsp;
        <el-switch v-model="form.autoFit" inactive-text="自适应铺满">
        </el-switch>
      </el-col>
    </el-row>
    <!-- 编辑面板 -->
    <div class="div-editpanel" v-loading="loading">
      <div
        class="draggablePanel-bg"
        v-bind:style="{
          width: form.width + 'px',
          height: form.height + 'px',
          transform: 'scale(' + form.scale + ')',
          '-webkit-transform': 'scale(' + form.scale + ')'
        }"
      >
        <componentPreview
          v-if="screenBackgroundView"
          :view="screenBackgroundView"
        ></componentPreview>
      </div>
      <div
        class="draggablePanel"
        v-bind:style="{
          width: form.width + 'px',
          height: form.height + 'px',
          transform: 'scale(' + form.scale + ')',
          '-webkit-transform': 'scale(' + form.scale + ')'
        }"
        v-if="isShowPanel"
      >
        <VueDraggableResizable
          :grid="[5, 5]"
          v-for="(item, index) in form.components"
          :key="index"
          v-show="item.show"
          :x="(item.position || {}).left || 0"
          :y="(item.position || {}).top || 0"
          :w="(item.position || {}).width || 100"
          :h="(item.position || {}).height || 100"
          :parent="true"
          :debug="false"
          :isConflictCheck="true"
          :active="index == activeIndex"
          :snap="true"
          :snapTolerance="20"
          v-on:resizing="(x, y, w, h) => onResize(x, y, w, h, index)"
          v-on:dragging="(x, y) => onDrag(x, y, index)"
          @activated="onActivated(index)"
          @deactivated="onDeactivated(index)"
        >
          <div class="div-edit-box">
            <div class="div-edit-content">
              <!-- <img
                style="width: 100%; height: 100%; "
                :src="((item.view || {}).cover || {}).fileId | getResourceUrl"
                class="image"
              /> -->

              <!-- <iframe
                src="http://localhost:8099/"
                style="width: 100%; height: 100%; overflow: hidden"
                frameborder="0"
                allowTransparency="true"
              ></iframe> -->

              <componentPreview :view="item.view"></componentPreview>
            </div>
            <div class="div-edit-madel">
              <!-- {{ (item.view || {}).name }}/{{ (item.view || {}).code }} -->
            </div>
          </div>
        </VueDraggableResizable>
      </div>
    </div>

    <!-- 属性面板 -->
    <div class="div-propertypanel">
      <div class="div-propertypanel-properties">
        <componentEdit
          :component="form.components[activeIndex]"
          v-if="activeIndex != null"
        ></componentEdit>
      </div>
      <div class="div-propertypanel-layers">
        <layers
          :components="form.components"
          :activeIndex="activeIndex"
          @onSelected="i => (activeIndex = i)"
          @change="coms => (form.components = coms)"
        ></layers>
        <br />
      </div>
    </div>

    <layerTemplatesForm
      ref="layerTemplatesForm"
      @ok-click="templateSelectedHandler"
    ></layerTemplatesForm>
  </div>
</template>

<script>
import { getList } from "@/api/table";
import resourceApi from "@/api/resource";
import componentEdit from "./componentEdit";
import componentPreview from "@/views/component/componentPreview";

//拖拽
import VueDraggableResizable from "vue-draggable-resizable";
import "vue-draggable-resizable/dist/VueDraggableResizable.css";

import positionEdit from "./positionEdit";
import layerTemplatesForm from "./layerTemplatesForm";
import layers from "./layers";
import { uuid } from "@/utils";
export default {
  components: {
    positionEdit,
    VueDraggableResizable,
    layerTemplatesForm,
    layers,
    componentEdit,
    componentPreview
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "gray",
        deleted: "danger"
      };
      return statusMap[status];
    },
    getResourceUrl(fileId) {
      return resourceApi.getResourceUrl(fileId);
    }
  },
  props: {
    closehandler: {
      type: Function,
      default: () => {}
    },
    id: ""
  },
  watch: {
    id() {
      this.loadData();
    }
  },
  computed: {
    showedComponents() {
      if (!this.form) return [];
      this.form.components = this.form.components || [];
      return this.form.components.filter(c => c.show);
    },
    screenBackgroundView() {
      let coms = this.form.components.filter(c => c.position.backgound);
      if (coms.length == 0) return null;
      return coms[0].view;
    }
  },
  data() {
    return {
      code: "",
      form: {
        autoFit: true,
        components: [
          // {
          //  name: "string",
          //  code: "string",
          //   id: "string",
          //   middleware: {
          //     description: "string",
          //     middleware: {
          //       fileId: "string",
          //       fileName: "string"
          //     },
          //     middlewareEntry: "string",
          //     name: "string",
          //     parameters: [
          //       {
          //         description: "string",
          //         isPublic: true,
          //         name: "string",
          //         required: true,
          //         value: "string"
          //       }
          //     ],
          //     push: true,
          //     updateFrequency: 0
          //   },
          //   order: 0,
          //   position: {
          //     bottom: 0,
          //     height: 0,
          //     backgound: 0,
          //     left: 0,
          //     right: 0,
          //     top: 0,
          //     width: 0
          //   },
          //   show: true,
          //   systemMiddleware: true,
          //   view: {
          //     code: "string",
          //     codes: "string",
          //     cover: {
          //       fileId: "string",
          //       fileName: "string"
          //     },
          //     description: "string",
          //     headLinks: "string",
          //     name: "string",
          //     resources: [
          //       {
          //         fileId: "string",
          //         fileName: "string"
          //       }
          //     ],
          //     screenViewSize: {
          //       height: 0,
          //       width: 0
          //     }
          //   }
          // }
        ],
        cover: {
          fileId: "string",
          fileName: "string"
        },
        height: 600,
        id: "string",
        name: "string",
        width: 1000,
        scale: 1
      },
      draggingPanel: {
        bottom: 0,
        height: 0,
        backgound: 0,
        left: 0,
        right: 0,
        top: 0,
        width: 0
      },
      loading: false,
      listLoading: true,
      isShowPanel: true,
      layervisible: true,
      activeIndex: null
    };
  },
  created() {
    this.listLoading = false;
  },
  mounted() {
    this.loadData();
    this.keyCodeForEvent();
  },
  methods: {
    goBack() {},
    loadData() {
      this.loading = true;
      // if (!this.id || this.id.length == 0) {
      //   this.form = {};
      //   return;
      // }
      this.$store
        .dispatch("screen/get", this.id || this.$route.query.id)
        .then(res => {
          res.components.forEach(com => {
            if (!com.position) {
              this.$set(com, "position", {
                bottom: 0,
                height: 50,
                backgound: 0,
                left: 0,
                right: 0,
                top: 0,
                width: 0
              });
            }
          });

          this.form = res;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    commit(callback) {
      this.loading = true;
      this.form.id = this.$route.query.id;
      this.$store
        .dispatch("screen/update", this.form)
        .then(res => {
          this.loading = false;
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        })
        .catch(() => {
          this.loading = false;
        });
    },
    onActivated(index) {
      this.activeIndex = index;
    },
    onDeactivated(index) {
      //this.activeIndex = null;
    },
    onResize(x, y, width, height, index) {
      let position = this.form.components[index].position;
      if (!position) {
        this.$set(this.form.components[index], "position", {
          bottom: 0,
          height: 0,
          backgound: 0,
          left: 0,
          right: 0,
          top: 0,
          width: 0
        });
        position = this.form.components[index].position;
      }
      position.top = y;
      position.left = x;
      position.width = width;
      position.height = height;
    },
    onDrag(x, y, index) {
      let position = this.form.components[index].position;
      if (!position) {
        this.$set(this.form.components[index], "position", {
          bottom: 0,
          height: 0,
          backgound: false,
          left: 0,
          right: 0,
          top: 0,
          width: 0
        });
        position = this.form.components[index].position;
      }
      position.top = y;
      position.left = x;
    },
    reloadPanel() {
      this.isShowPanel = false;
      setTimeout(() => {
        this.isShowPanel = true;
      }, 500);
    },
    getScreenPreviewUrl(id) {
      let url = resourceApi.getScreenPreviewUrl(id);
      window.open(url, "_bank");
    },
    templateSelectedHandler(ids) {
      this.loading = true;
      this.$store
        .dispatch("screen/importcomponents", { viewComponentIds: ids })
        .then(res => {
          res.forEach(r => {
            if (!r.position) {
              this.$set(r, "position", {
                bottom: 0,
                height: 50,
                backgound: false,
                left: 0,
                right: 0,
                top: 0,
                width: 0
              });
            }

            r.show = true;
            r.id = uuid();
            r.view.id = uuid();
            this.form.components.push(r);
          });

          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    layerDeleteHandler(index) {
      this.$confirm("是否删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        //删除图层
        this.form.components.splice(index, 1);
      });
    },
    keyCodeForEvent() {
      let self = this;
      document.onkeydown = function(e) {
        // console.log(e);
        let evn = e || event;
        let key = evn.keyCode || evn.which || evn.charCode;
        if (key === 83 && evn.ctrlKey) {
          //s  键 + ctrl
          self.commit();
          evn.preventDefault();
        }
      };
    }
  }
};
</script>
<style scoped>
.row-actions {
  position: absolute;
  top: 0px;
  width: 100%;
  margin: 5px;
  z-index: 10;
  height: 35px;
  box-shadow: 0px 2px 5px #cccccc;
}
.card-editconfig {
  position: absolute;
  top: 16px;
  margin: auto;
}
.div-editpanel {
  left: 0px;
  right: 400px;
  position: absolute;
  top: 50px;
  bottom: 0px;
  overflow: auto;
}
/**属性面板 */
.div-propertypanel {
  right: 0px;
  width: 400px;
  position: absolute;
  top: 40px;
  bottom: 0px;
  overflow: hidden;
  border-left: 2px solid #dddddd;
  border-top: 2px solid #dddddd;
}

.div-propertypanel-properties {
  top: 0px;
  height: 70%;
  width: 100%;
  overflow: auto;
}
.div-propertypanel-layers {
  height: 30%;
  width: 100%;
  bottom: 0px;
  overflow: hidden;
  /* overflow-y: scroll; */
  border-top: 2px solid #dddddd;
}

.div-layer {
  width: 180px;
  position: absolute;
  right: 20px;
  top: 40px;
  overflow: hidden;
  padding: 10px;
}

.row-layer {
  height: calc(100vh - 130px);
  overflow: hidden;
}
.draggablePanel-bg {
  position: absolute;
  left: 0px;
  top: 0px;
  background: linear-gradient(-90deg, rgba(0, 0, 0, 0.1) 1px, transparent 1px)
      0% 0% / 5px 5px,
    linear-gradient(rgba(0, 0, 0, 0.1) 1px, transparent 1px) 0% 0% / 5px 5px;
  transform-origin: 0 0 0;
  -webkit-transform-origin: 0, 0, 0;
}
.draggablePanel {
  position: absolute;
  left: 0px;
  top: 0px;
  transform-origin: 0 0 0;
  -webkit-transform-origin: 0, 0, 0;
}

.div-position {
  height: 60px;
  position: absolute;
  right: 200px;
  left: 10px;
  bottom: 20px;
  padding: 10px;
  overflow: hidden;
}
.div-edit-box {
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: relative;
  opacity: 0.7;
}
.div-edit-content {
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: relative;
}
.div-edit-madel {
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: absolute;
  z-index: 2;
  top: 0px;
}
</style>
<style>
.div-layer .el-card__body,
.div-position .el-card__body {
  padding: 0px !important;
}
</style>
